<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/02
 */

namespace app\admin\model;

use think\facade\Db;
use think\Model;
use app\common\exception\FailException;
use app\common\traits\ResponseJson;

class BaseModel extends Model
{

    private static $errorMsg;

    private static $transaction = 0;

    private static $DbInstance = [];
    //私有属性，用于保存实例
    protected static $instance;

    const DEFAULT_ERROR_MSG = '操作失败,请稍候再试!';


      /**
     * 更新前
     * @return mixed|void
     * @throws Exception
     */
    public static function onBeforeUpdate($model)
    {
        
    }

    /**
     * 写入前
     * @return mixed|void
     * @throws Exception
     */
    public static function onBeforeWrite($model)
    {
        
    }

    /**
     * 删除前
     * @return mixed|void
     * @throws Exception
     */
    public static function onBeforeDelete($model)
    {
        
    }

    /**
     * 新增前
     * @return mixed|void
     * @throws Exception
     */
    public static function onBeforeInsert($model)
    {
        
    }

        /**
     * 单例模式
     */
    public static function query()
    {
        //判断实例有无创建，没有的话创建实例并返回，有的话直接返回
        if ((static::$instance[static::class] ?? []) instanceof static) {
            return static::$instance[static::class];
        }
        static::$instance[static::class] = new static();

        return static::$instance[static::class];
    }
    /**
     * 设置错误信息
     * @param string $errorMsg
     * @return bool
     */
    protected static function setErrorInfo($errorMsg = self::DEFAULT_ERROR_MSG, $rollback = false)
    {
        if ($rollback) self::rollbackTrans();
        self::$errorMsg = $errorMsg;
        return false;
    }

    /**
     * 获取错误信息
     * @param string $defaultMsg
     * @return string
     */
    public static function getErrorInfo($defaultMsg = self::DEFAULT_ERROR_MSG)
    {
        return !empty(self::$errorMsg) ? self::$errorMsg : $defaultMsg;
    }

    /**
     * 开启事务
     */
    public static function beginTrans()
    {
        Db::startTrans();
    }

    /**
     * 提交事务
     */
    public static function commitTrans()
    {
        Db::commit();
    }

    /**
     * 关闭事务
     */
    public static function rollbackTrans()
    {
        Db::rollback();
    }

    /**
     * 根据结果提交滚回事务
     * @param $res
     */
    public static function checkTrans($res)
    {
        if ($res) {
            self::commitTrans();
        } else {
            self::rollbackTrans();
        }
    }


    
    /**
     * 获取时间段之间的model
     * @param int|string $time
     * @param string $ceil
     * @return array
     */
    public static function getModelTime($where, $model = null, $prefix = 'create_time', $data = 'data', $field = ' - ')
    {
        if ($model == null) $model = new self;
        if (!isset($where[$data])) return $model;
        switch ($where[$data]) {
            case 'today':
            case 'week':
            case 'month':
            case 'year':
            case 'yesterday':
                $model = $model->whereTime($prefix, $where[$data]);
                break;
            case 'quarter':
                list($startTime, $endTime) = self::getMonth();
                $model = $model->where($prefix, '>', strtotime($startTime));
                $model = $model->where($prefix, '<', strtotime($endTime));
                break;
            case 'lately7':
                $model = $model->where($prefix, 'between', [strtotime("-7 day"), time()]);
                break;
            case 'lately30':
                $model = $model->where($prefix, 'between', [strtotime("-30 day"), time()]);
                break;
            default:
                if (strstr($where[$data], $field) !== false) {
                    list($startTime, $endTime) = explode($field, $where[$data]);
                    $model = $model->where($prefix, '>', strtotime($startTime));
                    $model = $model->where($prefix, '<', bcadd(strtotime($endTime), 86400, 0));
                }
                break;
        }
        return $model;
    }

        /**
     * 获取本季度 time
     * @param int|string $time
     * @param string $ceil
     * @return array
     */
    public static function getMonth($time = '', $ceil = 0)
    {
        if ($ceil != 0)
            $season = ceil(date('n') / 3) - $ceil;
        else
            $season = ceil(date('n') / 3);
        $firstday = date('Y-m-01', mktime(0, 0, 0, ($season - 1) * 3 + 1, 1, date('Y')));
        $lastday = date('Y-m-t', mktime(0, 0, 0, $season * 3, 1, date('Y')));
        return array($firstday, $lastday);
    }

}